package cn.gz.coolshark.controller;

import cn.gz.coolshark.mapper.ProductMapper;
import cn.gz.coolshark.pojo.dto.ProductDTO;
import cn.gz.coolshark.pojo.entity.Product;
import cn.gz.coolshark.pojo.vo.ProductAdminVO;
import cn.gz.coolshark.pojo.vo.ProductDetailVO;
import cn.gz.coolshark.pojo.vo.ProductIndexVO;
import cn.gz.coolshark.pojo.vo.ProductTopVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/product/")
public class ProductController {
    @Autowired
    private ProductMapper productMapper;

    @RequestMapping("insert")
    public void insert(@RequestBody ProductDTO productDTO){
        //把dto的数据装进entity
        Product product = new Product();
        BeanUtils.copyProperties(productDTO,product);
        product.setViewCount(0);
        product.setCreated(new Date());
        //创建ProductMapper。实现insert方法
        productMapper.insert(product);
    }

    @RequestMapping("select")
    public List<ProductAdminVO> select(){
        return productMapper.selectForAdmin();
    }

    @RequestMapping("delete")
    public void delete(int id){
       String url =  productMapper.selectUrlById(id);
        System.out.println(url);
       new File("d:/files"+url).delete();
       productMapper.deleteById(id);
    }
    @RequestMapping("top")
    public List<ProductTopVO> top(){
        return productMapper.selectTop();
    }

    @RequestMapping("index")
    public List<ProductIndexVO> selectProductIndexVO(){
        return productMapper.selectForIndex();
    }

    @RequestMapping("detail")
    public ProductDetailVO selectDetail(int id){
        return productMapper.selectDetailById(id);
    }

    @RequestMapping("category")
    public List<ProductIndexVO> category(int id){
        return productMapper.selectByCategoryId(id);
    }

    @RequestMapping("search")
    public List<ProductIndexVO> search(String wd){
        return productMapper.selectByWd(wd);
    }
}
